package com.sram.dao;

import com.sram.entity.User;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate4.support.HibernateDaoSupport;

import java.io.Serializable;
import java.util.List;

/**
 * Created by Administrator on 2017/3/16.
 */
public class BaseDao extends HibernateDaoSupport {
    @Autowired
    public void setSessionFactoryOverride(SessionFactory sessionFactory) {
        super.setSessionFactory(sessionFactory);
    }

    public Session openSession() {
        Session session = this.getHibernateTemplate().getSessionFactory().openSession();
        // Session session = this.getHibernateTemplate().getSessionFactory().getCurrentSession();
        return session;
    }

    public Session getCurrentSession() {
        Session session = this.getHibernateTemplate().getSessionFactory().getCurrentSession();
        return session;
    }

    public void add(Object obj) throws Exception {
        Session session = this.getHibernateTemplate().getSessionFactory().getCurrentSession();
        session.save(obj);
    }

    public void update(Object obj) throws Exception {
        this.getHibernateTemplate().update(obj);
    }
    public void deleteById(Class userClass, Serializable id) throws Exception{
        Object o = findByid(userClass, id);
        delete(o);
    }
    public void delete(Object obj) throws Exception{
        this.getHibernateTemplate().delete(obj);
    }

    public List getAll(String userClass) {
        return this.getHibernateTemplate().find("from "+userClass);
    }

    public Object findByid(Class userClass, Serializable id) {
        return this.getHibernateTemplate().get(userClass,id);
    }
    public List getByParam(String queryString, Object[] values) {
        return this.getHibernateTemplate().find(queryString,values);
    }
}
